// jwt生成token
package jwt_util

import (
	jwt "github.com/dgrijalva/jwt-go"

	"time"
)

/**
JWT使用：
	token,_:=jwt.GenerateToken(username)
    fmt.Println("生成的token:",token)
    claim,err:=jwt.ParseToken(token)
    if err!=nil {
        fmt.Println("解析token出现错误：",err)
    }else if time.Now().Unix() > claim.ExpiresAt {
        fmt.Println("时间超时")
    }else {
        fmt.Println("username:",claim.Username)
    }
*/

// 不可泄漏
var jwtSecret = []byte("secret")

type Claims struct {
	Username string `json:"username"`
	jwt.StandardClaims
}

// 产生token的函数
func GenerateToken(username string) (string, error) {
	nowTime := time.Now()
	expireTime := nowTime.Add(3 * time.Hour)

	claims := Claims{
		username,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    "gin-blog",
		},
	}
	//
	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(jwtSecret)

	return token, err
}

// 验证token的函数
func GetToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}
	//
	return nil, err
}
